package cn.mothin.frame.util.encrypt;

import java.security.MessageDigest;

import org.apache.commons.logging.LogFactory;

import cn.mothin.frame.core.exception.SystemException;

public class MD5 {
	/**
     * MD5 加密
     * 
     * @param str 需加密的字符串
     * @return MD5加密后的字符串
     * @throws Exception
     */
    public static String makeMD5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (Exception e) {
    		LogFactory.getLog(MD5.class).error(e);
        	throw(new SystemException());
        }

        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }
    
    /**
     * MD5加密
     * @param str 被加密数据
     * @param count MD5运算次数
     * @return 加密后的字符串
     * @throws Exception
     */
    public static String makeMD5(String str,int count) throws Exception{
    	String result=str;
    	for(int i=0;i<count;i++){
    		result=makeMD5(result);
    	}
    	return result;
    }
}
